// 平台管理-mysql服务处理

// 引入数据库模块
const db = require('../../config/mysql.js')
const utils = require("../../common/utils")
const bcrypt = require('bcryptjs')


// 获取所有菜单
const getAllMenu = () => {
  return new Promise((resolve, reject) => {
    let sql = `select * from sys_menu`
    db.query(sql, (err, result) => {
      if (err) return reject(err)
      const menuList = utils.organizeMenuData(result)
      utils.sortMenu(menuList)
      return resolve(menuList)
    })
  })
}

// 添加菜单
const addMenu = (data) => {
  return new Promise((resolve, reject) => {
    let { name, path, icon, parent_id, order_by, status } = data
    let sql = `insert into sys_menu (name, path, icon, parent_id, order_by, status) values("${name}", "${path}", "${icon}", "${parent_id}", ${order_by}, ${status})`
    db.query(sql, (err, result) => {
      if (err) return reject(err)
      if (result.affectedRows == 1) return resolve("添加成功")
      return reject("添加失败")
    })
  })
}

// 修改菜单
const updateMenu = (data) => {
  return new Promise((resolve, reject) => {
    let { id, parent_id, name, path, icon, order_by, status } = data
    let sql = `update sys_menu set name = "${name}", path = "${path}", icon = "${icon}", parent_id = "${parent_id}", order_by = ${order_by}, status = ${status} where id = "${id}"`
    db.query(sql, (err, result) => {
      if (err) return reject(err)
      if (result.affectedRows == 1) return resolve("修改成功")
      return reject("修改失败")
    })
  })
}

// 删除菜单
const deleteMenu = (id) => {
  return new Promise((resolve, reject) => {
    // 判断是否有子级菜单,有就不能删除
    let sql = `select count(id) as sonCount from sys_menu where parent_id = ${id}`
    db.query(sql, (err, result) => {
      if (err) return reject(err)
      if (result[0].sonCount > 0) return reject("该菜单有子级菜单, 不能删除")
      let sql1 = `delete from sys_menu where id = ${id}`
      db.query(sql1, (err1, result1) => {
        if (err1) return reject(err1)
        if (result1.affectedRows == 1) {
          db.query(`delete from sys_role_menu where menu_id = ${id}`, (err2, result2) => {
            if (err2) return reject(err2)
            return resolve("删除成功")
          })
        } else {
          return reject("删除失败")
        }
      })
    })
  })
}



// 添加角色
const addRole = (data) => {
  return new Promise((resolve, reject) => {
    let sql = `insert into sys_role values("${data.id}", "${data.role_name}", "${data.description}", "${data.index_page}", "${data.sys_title}", 1)`
    db.query(sql, (err, result) => {
      if (err) return reject(err)
      if (result.affectedRows == 1) return resolve("添加角色成功")
      return reject("添加角色失败")
    })
  })
}

// 删除角色
const deleteRole = (id) => {
  return new Promise((resolve, reject) => {
    let sql0 = `select * from sys_role_menu where role_id = "${id}"`
    db.query(sql0, (err, result) => {
      if (err) return reject(err)
      // 有角色但没配权限
      if (result.length === 0) {
        let sql = `DELETE FROM sys_role WHERE id = "${id}"`
        db.query(sql, (err1, result1) => {
          if (err1) return reject(err1)
          if (result1.affectedRows == 1) return resolve("删除角色成功")
          return reject("删除角色失败")
        })
      } else {
        let sql = `DELETE FROM sys_role, sys_role_menu USING sys_role INNER JOIN sys_role_menu ON sys_role.id = sys_role_menu.role_id WHERE sys_role.id = "${id}"`
        db.query(sql, (err1, result1) => {
          if (err1) return reject(err1)
          return resolve("删除角色成功")
        })
      }
    })
  })
}

// 修改角色
const updateRole = (data) => {
  return new Promise((resolve, reject) => {
    let sql = `update sys_role set role_name = "${data.role_name}", description = "${data.description}", status = ${data.status}, index_page = "${data.index_page}", sys_title = "${data.sys_title}" where id = "${data.id}"`
    db.query(sql, (err, result) => {
      if (err) return reject(err)
      if (result.affectedRows == 1) return resolve("修改角色成功")
      return reject("修改角色失败")
    })
  })
}

// 获取角色列表
const getRoleList = (pageNum, pageSize, role_name) => {
  return new Promise((resolve, reject) => {
    let sql = ''
    let sql1 = ''
    if (role_name.trim() != '') {
      sql = `select * from sys_role where role_name like "%${role_name}%" limit ${pageSize} offset ${(pageNum - 1) * pageSize}`
      sql1 = `select count(*) as total from sys_role where role_name like "%${role_name}%"`
    } else {
      sql = `select * from sys_role limit ${pageSize} offset ${(pageNum - 1) * pageSize}`
      sql1 = `select count(*) as total from sys_role`
    }
    db.query(sql, (err, result) => {
      if (err) return reject(err)
      db.query(sql1, (err1, result1) => {
        if (err1) return reject(err1)
        return resolve({
          records: result,
          total: result1[0].total
        })
      })
    })
  })
}

// 获取角色菜单
const getRolePermission = (role_id) => {
  return new Promise((resolve, reject) => {
    // 获取所有菜单（未被禁用的）
    let sql = `select * from sys_menu where status = 1`
    db.query(sql, (err, result) => {
      if (err) return reject(err)
      result.forEach(item => item.status = 0)
      // 角色拥有的菜单
      let sql1 = `select menu_id from sys_role_menu where role_id = "${role_id}"`
      db.query(sql1, (err1, result1) => {
        if (err1) return reject(err1)
        if (result1.length != 0) {
          const menu = result1.map(item => item.menu_id)
          result.forEach(item => {
            if (menu.findIndex(el => el == item.id) != -1) {
              item.status = 1
            }
          })
        }
        const menuList = utils.organizeMenuData(result)
        utils.sortMenu(menuList)
        return resolve(menuList)
      })
    })
  })
}

// 配置角色权限（菜单）
const updateRolePermission = (role_id, menu_ids) => {
  return new Promise((resolve, reject) => {
    // 判断角色是否有菜单分配
    db.query(`select role_id from sys_role_menu where role_id = "${role_id}"`, (err, result) => {
      if (err) return reject(err)
      // 先删除该角色的所有旧菜单
      db.query(`DELETE FROM sys_role_menu WHERE role_id = "${role_id}"`, (err1, result1) => {
        if (err1) return reject(err1);
        // 如果菜单 ID 数组为空，直接返回成功
        if (menu_ids.length === 0) return resolve("配置成功");
        // 遍历数组生成插入语句
        let values = menu_ids.map(menu_id => `("${role_id}", "${menu_id}")`).join(", ");
        let sql = `INSERT INTO sys_role_menu (role_id, menu_id) VALUES ${values}`;
        db.query(sql, (err2, result2) => {
          if (err2) return reject(err2);
          if (result2.affectedRows === menu_ids.length) return resolve("配置成功");
          return reject("配置失败");
        });
      });
    })
  })
}



// 添加用户
const addUser = (data) => {
  return new Promise((resolve, reject) => {
    let uuid = utils.generateId()
    let key = utils.generateKey()
    let secret = utils.generateSecret()
    let register_time = utils.formatDate(new Date().getTime())

    let { email, password, role_id, status } = data
    // 是否已存在
    db.query(`select email from sys_user where email = "${email}"`, (err, result) => {
      if (err) return reject(err)
      if (result.length >= 1) return reject("用户已存在")
      // 加密
      password = bcrypt.hashSync(password, 10)
      let sql = `insert into sys_user (id, nickName, email, password, role_id, keyId, secretKey, status, register_time) values("${uuid}","${email}","${email}","${password}","${role_id}","${key}","${secret}","${status}","${register_time}")`
      db.query(sql, (err1, result1) => {
        if (err1) return reject(err1)
        if (result1.affectedRows == 1) return resolve("添加用户成功")
        return reject("添加用户失败")
      })
    })
  })
}

// 删除用户
const deleteUser = (id) => {
  return new Promise((resolve, reject) => {
    let sql = `delete from sys_user where id = "${id}"`
    db.query(sql, (err, result) => {
      if (err) return reject(err)
      if (result.affectedRows == 1) return resolve("删除成功")
      return reject("删除失败")
    })
  })
}

// 修改用户
const updateUser = (data) => {
  return new Promise((resolve, reject) => {
    let { id, email, role_id, status } = data
    let sql = `update sys_user set email = "${email}", role_id = "${role_id}", status = ${status} where id = "${id}"`
    db.query(sql, (err, result) => {
      if (err) return reject(err)
      if (result.affectedRows == 1) return resolve("修改成功")
      return reject("修改失败")
    })
  })
}

// 重置用户密码(1-6)
const resetPassword = (id) => {
  return new Promise((resolve, reject) => {
    let password = bcrypt.hashSync("123456", 10)
    let sql = `update sys_user set password = "${password}" where id = "${id}"`
    db.query(sql, (err, result) => {
      if (err) return reject(err)
      if (result.affectedRows == 1) return resolve("密码重置成功")
      return reject("密码重置失败")
    })
  })
}

// 获取用户列表
const getUserList = (data) => {
  return new Promise((resolve, reject) => {
    let { email, role_id, status, pageNum, pageSize } = data
    let countSql = `select count(id) as total from sys_user`
    let listSql = `select * from sys_user`
    let conditions1 = []
    let conditions2 = []
    if (email != '' && email != undefined) {
      conditions1.push(`email like "%${email}%"`)
      conditions2.push(`email like "%${email}%"`)
    }
    if (role_id != '' && role_id != undefined) {
      conditions1.push(`role_id = "${role_id}"`)
      conditions2.push(`role_id = "${role_id}"`)
    }
    if (status != '' && status != undefined) {
      conditions1.push(`status = "${status}"`)
      conditions2.push(`status = "${status}"`)
    }
    if (conditions1.length > 0) {
      listSql += " where " + conditions1.join(' and ')
      countSql += " where " + conditions2.join(' and ')
    }
    listSql += ` limit ${pageSize} offset ${(pageNum - 1) * pageSize}`
    db.query(listSql, (err, result) => {
      result.forEach(item => {
        delete item.password
      })
      if (err) return reject(err)
      db.query(countSql, (err1, result1) => {
        if (err) return reject(err)
        return resolve({
          records: result,
          total: result1[0].total
        })
      })
    })
  })
}

module.exports = {
  getRoleList,
  addRole,
  deleteRole,
  updateRole,
  getRolePermission,
  updateRolePermission,
  getAllMenu,
  addMenu,
  updateMenu,
  deleteMenu,
  addUser,
  deleteUser,
  updateUser,
  resetPassword,
  getUserList,
}